#!/bin/bash
# PodClip Helper for macOS. Opening the app (or a podclip-helper:// link) runs this:
# 1. copies the helper out of the app into ~/Library/Application Support (macOS runs apps from the internet from a
#    temporary read-only place, so starting at login needs its own copy), 2. sets it to start at login,
# 3. starts it if it isn't running, 4. the first time, opens its status page.
set -u
RES="$(cd "$(dirname "$0")/../Resources" && pwd)"
SUP="$HOME/Library/Application Support/PodClip Helper"
AGENT="$HOME/Library/LaunchAgents/app.podclip.helper.plist"
VERSION="$(cat "$RES/VERSION" 2>/dev/null || echo 0)"
mkdir -p "$SUP/downloads" "$HOME/Library/LaunchAgents"

if [ "$(cat "$SUP/VERSION" 2>/dev/null)" != "$VERSION" ]; then
  # a new or updated copy: stop the old one, copy the runtime, yt-dlp and the helper (without macOS's download flag)
  curl -s -X POST --max-time 2 http://localhost:4317/api/quit >/dev/null 2>&1
  sleep 1
  for f in node yt-dlp helper.mjs VERSION; do cp -X "$RES/$f" "$SUP/$f"; done
  chmod 755 "$SUP/node" "$SUP/yt-dlp"
  xattr -dr com.apple.quarantine "$SUP" 2>/dev/null
  printf '{"root":"%s","bin":"%s","downloads":"%s/downloads","version":"%s"}\n' "$SUP" "$SUP" "$SUP" "$VERSION" > "$SUP/podclip-helper.json"
  FIRST=1
fi

cat > "$AGENT" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>app.podclip.helper</string>
  <key>ProgramArguments</key><array><string>$SUP/node</string><string>$SUP/helper.mjs</string></array>
  <key>RunAtLoad</key><true/>
  <key>StandardOutPath</key><string>$SUP/helper.log</string>
  <key>StandardErrorPath</key><string>$SUP/helper.log</string>
</dict></plist>
PLIST

if ! curl -s --max-time 2 http://localhost:4317/api/health >/dev/null 2>&1; then
  launchctl bootout "gui/$(id -u)/app.podclip.helper" >/dev/null 2>&1
  launchctl bootstrap "gui/$(id -u)" "$AGENT" >/dev/null 2>&1 || nohup "$SUP/node" "$SUP/helper.mjs" >>"$SUP/helper.log" 2>&1 &
  for i in $(seq 1 30); do curl -s --max-time 1 http://localhost:4317/api/health >/dev/null 2>&1 && break; sleep 0.5; done
fi
[ "${FIRST:-0}" = "1" ] && open "http://localhost:4317/"
exit 0
